import { routes } from "@/router";
import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import routerUtils from '@/utils/router'
import storage from "@/utils/storage";
import { useSelector } from "react-redux";

/**
 * 身份验证
*/
export function useCheckAuth() {
  const location = useLocation(),
    query = new URLSearchParams(location.search),
    navigate = useNavigate()

  const token = useSelector((state: any) => state.userModule.token)
  const [checkFinished, setCheckFinished] = useState<boolean>(false)

  const checkAuth = () => {
    console.log('用户登录后的token: ', token)
    // 处理携带的 token
    if (query.has('token')) {
      storage.sessionStorage.set('token', query.get('token')!)
      setCheckFinished(true)
      return
    }

    // 处理统一认证的 code
    if (query.has('code')) {
      // 发起请求验证信息
      return new Promise((resolve) => setTimeout(() => resolve({ code: 200, msg: 'ok', data: {} }), 5000))
      .then(() => {
      }).catch(() => {
        navigate('/login', { replace: true })
      }).finally(() => setCheckFinished(true))
    }

    // 本地没有 token
    if (!token) {
      navigate('/login', { replace: true })
      setCheckFinished(true)
      return
    }

    if (location.pathname === '/404' || location.pathname === '/login') {
      setCheckFinished(true)
      return
    }

    setCheckFinished(true)
  }

  useEffect(() => {
    try {
      checkAuth()
    } catch (error) {
      console.error(error)
      navigate('/error', { replace: true })
    }
  }, [location.pathname])

  return [checkFinished] as const
}

/**
 * 根据路由 meta 信息，动态设置一些属性
*/
export function useRouteMeta() {
  const location = useLocation()

  const routeInfo = routerUtils.findRouteInfo(routes, location.pathname)
  if (!routeInfo || !(routeInfo as any).meta) return

  const meta = (routeInfo as any).meta

  document.title = meta?.title || import.meta.env.VITE_APP_TITLE
}